﻿using System;
using System.Text.RegularExpressions;
using Wireframe;

namespace SampleWebCrawler
{
    /// <summary>
    ///     Represents an event handler for message parsing events.
    /// </summary>
    public sealed class HtmlParser
    {
        private const string UriRegex = @"(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?";

        /// <summary>
        ///     Handles message parsing events.
        /// </summary>
        /// <param name="message">Event data with HTML.</param>
        public void HandleParseHtmlEvent(ParseHtmlEvent message)
        {
            // This method will be called when "ParseHtmlEvent" is sent.

            var regex = new Regex(UriRegex);
            foreach (Match match in regex.Matches(message.Value))
            {
                Uri raw;
                if (Uri.TryCreate(match.Value, UriKind.Absolute, out raw))
                {
                    string uri = raw.AbsoluteUri;
                    string query = raw.Query;
                    if (!string.IsNullOrEmpty(query))
                    {
                        uri = uri.Replace(query, string.Empty);
                    }
                    // When new URI is discovered send "LoadHtmlEvent".
                    this.Send(new NewUriEvent(uri));
                }
            }
        }
    }
}